/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var TgTypeModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`type_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '类型ID',
  //`parent` bigint(20) DEFAULT NULL COMMENT '父类型id，根节点为空',
  //`type_name` varchar(20) NOT NULL DEFAULT '' COMMENT '类型名',
  //`state` int(2) NOT NULL DEFAULT '1' COMMENT '1新建,2可制作模版,3可对外发布',
  //`icon` text COMMENT '类型图标',
  //`order` int(3) NOT NULL DEFAULT '999' COMMENT '显示顺序',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0',


};
TgTypeModel.prototype = new ItbBaseModel();

// 取得表名
TgTypeModel.prototype.getTableName = function(){
    return 'tg_type';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
TgTypeModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'type_id='+this.type_id;
}

//------------------------------------------------------------------
/* 根据大分类获取所有分类信息
 * 参数:callback:回调
 * 返回二级结构
    [
        {
            id: 10,
            name: "邀请函",
            sub:[{id:101, name:“开业”}, {id:102, name:"讲座"} ...]
        },
        {
            id: 30,
            name: "招聘",
            sub:[{id:301, name:“校招”}, {id:302, name:"社招"} ...]
        }
    ]
 *
 * 参数 typeL: 大分类(默认为: 1竖屏)
 * 参数 typeM[可选]: 逗号链接中分类(例: 10邀请函)
 * 参数 typeS[可选]: 逗号链接小分类(例: 101开业)
 * 参数 withAny: 1:添加小分类“任意”
 * */
TgTypeModel.prototype.getTypeInfoByLMS = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = ' select s.type_id as sId, s.type_name as sName, m.type_id as mId, m.type_name as mName '+
            ' from tg_type m, tg_type s '+
            ' where m.del_flg=0 and s.del_flg=0 '+
            ' and m.type_id=s.parent '+
            ' and m.parent= '+ (THIS.typeL||1);

        if(!!THIS.typeM){
            sql += ' and s.parent IN ('+ THIS.typeM + ') ';
        }
        if(!!THIS.typeS){
            sql += ' and s.type_id IN ('+ THIS.typeS + ') ';
        }
        if(!!THIS.state){
            sql += ' and m.state='+THIS.state+' ';
            sql += ' and s.state='+THIS.state+' ';
        }
        sql += ' order by m.order, s.order ';

        //var sqlValue = [THIS.type_id];
        //sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();

            if(result && result.length>0){
                var retInfo = [];
                var sub = new Array();
                if(!!THIS.withAny){
                    sub.push({id: -1, name:"不限"});
                }
                var mId=result[0].mId;
                var mName=result[0].mName;

                for(var i in result){
                    if(mId != result[i].mId) {
                        retInfo.push({
                            id: mId,
                            name: mName,
                            sub: sub
                        });

                        mId = result[i].mId;
                        mName = result[i].mName;
                        sub = new Array();
                        if(!!THIS.withAny){
                            sub.push({id: -1, name:"不限"});
                        }
                    }

                    sub.push({
                        id: result[i].sId,
                        name: result[i].sName
                    });

                    if(i==result.length-1) {// 最后一条
                        retInfo.push({
                            id: mId,
                            name: mName,
                            sub: sub
                        });
                    }
                }

                callback(error, retInfo);

            }else{
                callback(error, null);
            }
        });
    });
}
//--------------------------------end-------------------------------

//------------------------------------------------------------------
/* 根据父分类获取子分类信息
 * 参数:callback:回调
 * 参数 parent: 大/中分类(默认为: 1竖屏)
 * */
TgTypeModel.prototype.getTypeInfoByParent = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = ' select t.type_id, t.type_name, t.icon '+
            ' from tg_type t '+
            ' where t.del_flg=0 '+
            ' and t.parent = '+ (THIS.parent||1) ;
        if(Number(THIS.state||'0')>0) {
            sql += ' and t.state='+THIS.state;
        }
        sql += ' order by t.order ';

        //var sqlValue = [THIS.type_id];
        //sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();

            if(result && result.length>0){
                callback(error, result);

            }else{
                callback(error, null);
            }
        });
    });
}
//--------------------------------end-------------------------------

//------------------------------------------------------------------
/* 根据父分类获取子分类信息(Design页面用)
 * 参数:callback:回调
 * 参数 parent: 大/中分类(默认为: 1竖屏)
 * */
TgTypeModel.prototype.getTypeInfoByParent4Design = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = ' select t.type_id, t.type_name '+
            ' from tg_type t '+
            ' where t.del_flg=0 AND t.state IN (2,3) '+
            ' and t.parent = '+ (THIS.parent||1) +
            ' order by t.order ';

        //var sqlValue = [THIS.type_id];
        //sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();

            if(result && result.length>0){
                callback(error, result);

            }else{
                callback(error, null);
            }
        });
    });
}
//--------------------------------end-------------------------------
/**
 * 获取当前分类信息
 *
 * @param parent 父级分类 id, 获取一级分类时, 传递 null, 获取二级分类,传递一级分类 id, 获取三级分类, 传递二级分类 id
 * @param callback 回调
 *              err: 错误
 *              results: 分类信息
 *
 * */
TgTypeModel.prototype.getCurrentTypeInfo = function(parent,callback) {

    pool.pool.getConnection(function(err, connection) {
        if(err) return callback(err, null);
        // Use the connection
        var sql = " select t.type_id as id, t.type_name as name, if(t.icon is null, '', t.icon) as icon, \"\" as adThumb, t.state as state from tg_type t where t.parent ";
        if(!parent) {
            sql += " is null ";
        } else {
            sql += " = " + parent;
        }
        sql += " and t.state>1 and t.del_flg=0 order by t.order ";

        //var sqlValue = [THIS.type_id];
        //sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();
            if(result && result.length>0){
                callback(error, result);

            }else{
                callback(error, null);
            }
        });
    });
};
/* 根据designId获取123及分类名和id
 * 参数:callback:回调
 * 参数 parent: 大/中分类(默认为: 1竖屏)
 * */
TgTypeModel.prototype.getTypeInfoByDesignId = function(designId,callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = "	SELECT 	" +
            "	r.*,	" +
            "	itt.type_name AS typeLname	" +
            "	FROM	" +
            "	(SELECT	" +
            "	  tt.type_name,	" +
            "	  tt.top_parent,	" +
            "	  tt.parent,	" +
            "	  tt.type_id,	" +
            "	  it.type_name AS typeMname	" +
            "	FROM	" +
            "	  itbour.tg_design_doc tdd,	" +
            "	  itbour.tg_type tt	" +
            "	  LEFT JOIN itbour.tg_type it ON it.type_id = tt.parent 	" +
            "	WHERE tdd.design_id = "+designId+" "+
            "	  AND tdd.type_id= tt.type_id 	" +
            "	  AND tdd.del_flg = 0	" +
            "	  AND tt.del_flg = 0) r	" +
            "	  LEFT JOIN itbour.tg_type itt ON itt.type_id = r.top_parent	" +
            "     limit 1   ";
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();
            if(result && result.length>0){
                callback(error, result);
            }else{
                callback(error, null);
            }
        });
    });
}

// 导出
module.exports = TgTypeModel;